package com.example.ivideo_2211a.broadcast

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.example.ivideo_2211a.R

/**
 * 直播预播提醒广播接收器
 * 用于接收和处理直播预播提醒的广播消息
 */
class LivePreNotificationReceiver : BroadcastReceiver() {
    
    companion object {
        const val ACTION_LIVE_PRE_NOTIFICATION = "com.example.ivideo_2211a.LIVE_PRE_NOTIFICATION"
        const val EXTRA_LIVE_TITLE = "live_title"
        const val EXTRA_LIVE_TIME = "live_time"
        const val TAG = "LivePreNotification"
        const val CHANNEL_ID = "live_notification_channel"
        const val NOTIFICATION_ID = 1001
    }
    
    override fun onReceive(context: Context?, intent: Intent?) {
        if (context == null || intent == null) return
        
        when (intent.action) {
            ACTION_LIVE_PRE_NOTIFICATION -> {
                handleLivePreNotification(context, intent)
            }
        }
    }
    
    /**
     * 处理直播预播提醒
     */
    private fun handleLivePreNotification(context: Context, intent: Intent) {
        val liveTitle = intent.getStringExtra(EXTRA_LIVE_TITLE) ?: "直播"
        val liveTime = intent.getStringExtra(EXTRA_LIVE_TIME) ?: "现在"
        
        Log.d(TAG, "收到直播预播提醒: $liveTitle, 时间: $liveTime")
        
        // 创建通知渠道（Android 8.0及以上需要）
        createNotificationChannel(context)
        
        // 显示通知栏通知
        showNotification(context, liveTitle, liveTime)
    }
    
    /**
     * 创建通知渠道（Android 8.0及以上需要）
     */
    private fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "直播通知"
            val descriptionText = "直播预告和提醒通知"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
                enableVibration(true)
                enableLights(true)
            }
            
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 显示通知栏通知
     */
    private fun showNotification(context: Context, liveTitle: String, liveTime: String) {
        try {
            // 创建点击通知的Intent（可以跳转到直播页面）
            val intent = Intent().apply {
                setClassName(context, "com.example.ivideo_2211a.activity.StartLiveActivity")
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            }
            
            val pendingIntent = PendingIntent.getActivity(
                context,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            
            // 构建通知
            val notification = NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_info) // 使用系统图标，可以替换为自定义图标
                .setContentTitle("📺 直播预告")
                .setContentText("$liveTitle 将在 $liveTime 开始直播！")
                .setStyle(NotificationCompat.BigTextStyle()
                    .bigText("$liveTitle 将在 $liveTime 开始直播！\n\n点击查看直播详情"))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setVibrate(longArrayOf(0, 500, 200, 500))
                .setContentIntent(pendingIntent)
                .build()
            
            // 显示通知
            val notificationManager = NotificationManagerCompat.from(context)
            notificationManager.notify(NOTIFICATION_ID, notification)
            
            Log.d(TAG, "通知已发送: $liveTitle at $liveTime")
            
        } catch (e: Exception) {
            Log.e(TAG, "发送通知失败", e)
        }
    }
}